/**
 * @description: 异步控制并发数
 */
class LimitRequest {
  constructor(limit) {
    this.taskList = []
    this.limit = limit
    this.doing = 0
  }

  get(url) {
    return new Promise(resolve => {
      const fn = () => {
        fetch(url).then(res => {
          resolve(res)
          this.doing--
          this.handleTask()
        })
      }
      this.taskList.push(fn)
      this.handleTask()
    })
  }

  handleTask() {
    if (this.taskList.length > 0) {
      if (this.doing < this.limit) {
        const fn = this.taskList.shift()
        this.doing++
        fn()
      }
    }
  }
}

export default LimitRequest
